package com.ruoyi.common.utils;

import lombok.Data;

import java.math.BigDecimal;

/**
 * @author 10100
 * @date 2020/5/18 13:56
 * @description 区域边界经纬度
 */
@Data
public class Polygon {

    private double[][] points;
    private int pointsLength;

    public Polygon() {

    }

    public Polygon(double[][] points) {
        this.points = points;
        this.pointsLength = points.length;
    }

    /**
     * 判断点位是否在区域内
     *
     * @param x 经度
     * @param y 纬度
     * @return boolean
     */
    public boolean contains(double x, double y) {

        int hits = 0;

        double lastx = points[pointsLength - 1][0];
        double lasty = points[pointsLength - 1][1];
        double curx, cury;

        // Walk the edges of the polygon
        for (int i = 0; i < pointsLength; lastx = curx, lasty = cury, i++) {
            curx = points[i][0];
            cury = points[i][1];

            float diff = 1e-6f;
            if (Math.abs(cury - lasty) < diff) {
                continue;
            }

            double leftx;
            if (curx < lastx) {
                if (x >= lastx) {
                    continue;
                }
                leftx = curx;
            } else {
                if (x >= curx) {
                    continue;
                }
                leftx = lastx;
            }

            double test1, test2;
            if (cury < lasty) {
                if (y < cury || y >= lasty) {
                    continue;
                }
                if (x < leftx) {
                    hits++;
                    continue;
                }
                test1 = x - curx;
                test2 = y - cury;
            } else {
                if (y < lasty || y >= cury) {
                    continue;
                }
                if (x < leftx) {
                    hits++;
                    continue;
                }
                test1 = x - lastx;
                test2 = y - lasty;
            }

            if (test1 < (test2 / (lasty - cury) * (lastx - curx))) {
                hits++;
            }
        }

        return ((hits & 1) != 0);
    }

    /**
     * 将经纬度字符转换为数据
     *
     * @param polygonString 经纬度字符串
     * @return double[][]
     */
    public static double[][] buildPath(String polygonString) {
        /*build 区域经纬度串 double[][]*/
        String[] polygonPoints = polygonString.split(";");
        double[][] polygons = new double[polygonPoints.length][2];
        for (int i = 0; i < polygonPoints.length; i++) {
            BigDecimal bg;
            String[] point = polygonPoints[i].toLowerCase().split(",");
            double[] points = new double[2];
            bg = new BigDecimal(point[0]);
            points[0] = bg.doubleValue();
            bg = new BigDecimal(point[1]);
            points[1] = bg.doubleValue();
            polygons[i] = points;
        }
        return polygons;
    }
}